//
//  UserModel.m
//  Cycling
//
//  Created by cjg.mini on 2023/3/5.
//

#import "UserModel.h"
#import <objc/message.h>

#define kPathForUserData  [NSDocumentsFolder() stringByAppendingPathComponent:@"CUser_data"]

@implementation UserModel

+ (instancetype)sharedInstance {
    static UserModel *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[UserModel alloc] init];
    });
    return instance;
}
#pragma mark - NSCoding
- (void )encodeWithCoder:(NSCoder *)aCoder {
    unsigned int count = 0; Ivar *ivars = class_copyIvarList([UserModel class], &count);
    for (int i = 0; i < count; i++) {
        Ivar ivar = ivars[i];
        const char *name = ivar_getName(ivar);
        NSString *key = [NSString stringWithUTF8String:name];
        id value = [self valueForKey:key];
        [aCoder encodeObject:value forKey:key];
    }
    free(ivars);
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super init]) {
        unsigned int count = 0;
        Ivar *ivars = class_copyIvarList([UserModel class], &count);
        for (int i = 0; i < count; i++) {
            Ivar ivar = ivars[i];
            const char *name = ivar_getName(ivar);
            NSString *key = [NSString stringWithUTF8String:name];
            id value = [aDecoder decodeObjectForKey:key];
            [self setValue:value forKey:key];
        }
        free(ivars);
        
    }
    return self;
}


// 登录成功或重新获取用户信息-->更新数据
- (BOOL)updateUserInfo{
    return [NSKeyedArchiver archiveRootObject:self toFile:kPathForUserData];
}
// 获取当前用户
+ (UserModel *)currentUserInfo{
    
    UserModel *curLoginUser = nil;
    curLoginUser = [NSKeyedUnarchiver unarchiveObjectWithFile:kPathForUserData];
    return curLoginUser?:[[UserModel alloc]init];// 为了防止调用user_name为nil导致crash
}
+ (BOOL)isLogin{
    return [USERDEFAULTS boolForKey:@"isUserDidLogin"];
}

+ (void)setLoginSatus:(BOOL)login{
    
    [USERDEFAULTS setBool:login forKey:@"isUserDidLogin"];
    [USERDEFAULTS synchronize];
}

@end
